package object

import (
	"fmt"

	"bilinadmin/internal/model"
)

// Permissions 权限
type Permissions struct {
	RouterMap  map[string]*model.Permission
	IdMap      map[int64]*model.Permission
	BrandPerms []*model.Permission
	StorePerms []*model.Permission
}

func buildPermRouterKey(perType int8, router string) string {
	return fmt.Sprintf("%d:%s", perType, router)
}

// NewPermissions 新建权限路由
func NewPermissions(perms []*model.Permission) *Permissions {
	routerMap := make(map[string]*model.Permission, len(perms))
	idMap := make(map[int64]*model.Permission, len(perms))
	var brandPerms []*model.Permission
	var storePerms []*model.Permission
	for _, p := range perms {
		routerMap[buildPermRouterKey(p.PerType, p.Router)] = p
		idMap[p.Id] = p
		if p.PerType == model.RefTypeBrand {
			brandPerms = append(brandPerms, p)
		} else if p.PerType == model.RefTypeStore {
			storePerms = append(storePerms, p)
		}
	}
	return &Permissions{
		RouterMap:  routerMap,
		IdMap:      idMap,
		BrandPerms: brandPerms,
		StorePerms: storePerms,
	}
}

// GetPermissionIdByRouter 根据 router 获取 PermissionId
func (p *Permissions) GetPermissionIdByRouter(perType int8, router string) int64 {
	per, ok := p.RouterMap[buildPermRouterKey(perType, router)]
	if !ok {
		return 0
	}
	return per.Id
}

// GetPermissionById 根据 id 获取
func (p *Permissions) GetPermissionById(id int64) *model.Permission {
	per, ok := p.IdMap[id]
	if !ok {
		return &model.Permission{}
	}
	return per
}

// RolePerm 角色权限
type RolePerm struct {
	// 角色id
	RoleId int64 `json:"role_id,omitempty"`
	// 权限id
	PerId int64 `json:"per_id"`
	// 权限类型
	PerType string `json:"per_type"`
	// 权限名
	PerName string `json:"per_name"`
	// 权限路由
	Router string `json:"router"`
}

// RoleInfo 角色信息
type RoleInfo struct {
	// 角色id
	RoleId int64 `json:"role_id"`
	// 角色名
	RoleName string `json:"role_name"`
	// 是否是管理员
	IsAdmin bool `json:"is_admin"`
	// 权限内容
	Permissions []*RolePerm `json:"permissions"`
}
